package com.sike.controller;

import com.sike.entity.Order;
import com.sike.entity.User;
import com.sike.service.OrderService;
import com.sike.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    private User user;

    // 创建订单
    @PostMapping("/create")
    public ResponseEntity<?> createOrder(@RequestBody Order order) {
        System.out.println("收到的订单总价: " + order.getTotalPrice());
        logger.info("收到的命令: {}", order);
        try {
            orderService.createOrder(order);
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            logger.error("创建订单时出错: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("创建订单时出错: " + e.getMessage());
        }
    }

    // 获取所有订单
    @GetMapping("")
    public ResponseEntity<List<Order>> getAllOrders() {
        List<Order> orders = orderService.findAllOrders();
        return ResponseEntity.ok(orders);
    }

    // 取消订单
    @DeleteMapping("/cancel/{orderId}")
    public ResponseEntity<?> cancelOrder(@PathVariable Integer orderId) {
        try {
            // 调用订单服务取消订单
            orderService.cancelOrder(orderId);

            // 返回成功取消订单的消息
            return ResponseEntity.ok("订单成功取消");


        } catch (Exception e) {
            // 如果取消订单时出现异常，记录错误并返回服务器错误消息
            logger.error("取消订单时出错: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("取消订单时出错: " + e.getMessage());
        }
    }


    @GetMapping("/{orderId}/details")
    public ResponseEntity<?> getOrderDetails(@PathVariable Integer orderId) {
        try {
            logger.info("Fetching details for order ID: {}", orderId);
            Order order = orderService.getOrderDetails(orderId);
            if (order != null) {
                logger.info("Order found: {}", order);
                return ResponseEntity.ok(order);
            } else {
                logger.warn("No order found for ID: {}", orderId);
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("Error retrieving order details for ID: {}: {}", orderId, e.getMessage(), e);
            return ResponseEntity.badRequest().body("获取订单详情错误: " + e.getMessage());
        }
    }

}
